package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.management.aop.anno.LogAnno;
import com.qk.management.aop.anno.ReportAnno;
import com.qk.management.mapper.OperateLogMapper;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author ZgYn
 * @Date 2025/10/17 18:43
 * @Name ReportAspect
 */
@Slf4j
@Aspect
@Component
public class ReportAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.qk.management.aop.anno.ReportAnno)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue = null;
        Class<?> targetClass = pjp.getTarget().getClass();
        String name = pjp.getSignature().getName();
        Method method = targetClass.getMethod(name);
        ReportAnno annotation = method.getAnnotation(ReportAnno.class);
        String redisKey = annotation.keyPrefix() + annotation.key();
        try {
            String JsonStr = redisTemplate.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(JsonStr)) {
                return JSONUtil.toBean(JsonStr, PortalVO.class);
            }
        } catch (Exception e) {
            log.error("查询缓存异常", e);
        }
        log.info("ReportAspect around");
        returnValue = pjp.proceed();
        try {
            String jsonStr = JSONUtil.toJsonStr(returnValue);
            redisTemplate.opsForValue().set(redisKey, jsonStr);
            redisTemplate.expire(redisKey, annotation.expireTime(), annotation.expireTimeUnit());
        } catch (Exception e) {
            log.error("添加缓存数据异常", e);
        }
        return returnValue;
    }
}
